import { toRefs, reactive, computed, onUnmounted, onMounted, ref } from 'vue';
import {getBrowerInfo, MD5} from '@/utils/util';
import validate from '@/utils/validate';
import { formatAxis } from '@/utils/formatTime';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { initFrontEndControlRoutes } from '@/router/frontEnd';
import { initBackEndControlRoutes } from '@/router/backEnd';
import store from '@/store';
import { Session } from '@/utils/storage';
import type { ElForm } from 'element-plus';
import { NextLoading } from '@/utils/loading';
type FormInstance = InstanceType<typeof ElForm>;
const ruleFormRef = ref<FormInstance>();
// 定义接口来定义对象的类型
interface LoginState {
	cellphone: string | number;
	shortMsgCode: string | number | undefined;
	userType: string;
	userPassword:string | undefined | null;
}

// 定义对象与类型
const ruleForm: LoginState = {
	cellphone: '',
	shortMsgCode: '',
	userType: '10',
	userPassword:''
};

export default function () {
	const checkPhone = (rule: any, value: any, callback: any) => {
		if (!value) {
			return callback(new Error('请输入的手机号码！'));
		}
		if (!validate.isPhone(state.ruleForm.cellphone)) {
			callback(new Error('请输入正确的手机号码'));
		} else {
			callback();
		}
	};
	const route = useRoute();
	const router = useRouter();
	const captchaImageContainer = ref<HTMLElement | null>(null);

	const state = reactive({
		ruleForm: ruleForm,
		rules: {
			cellphone: [{ validator: checkPhone, trigger: 'blur' }],
			shortMsgCode: [
				{
					required: true,
					message: '短信验证码不能为空',
					trigger: 'change',
				},
			],
		},
		rulesPassword: {
			cellphone: [{ validator: checkPhone, trigger: 'blur' }],
			userPassword: [
				{
					required: true,
					message: '密码不能为空',
					trigger: 'blur',
				},
			],
			shortMsgCode: [
				{
					required: true,
					message: '短信验证码不能为空',
					trigger: 'change',
				},
			],
		},
		disableCodeBtn: false,
		msgForm: {
			time: 60,
			loginBtn: false,
			smsSendBtn: false,
			smsText: '获取验证码',
		},
		originalImgSrc: '',
		sliderImgSrc: '',
		loading: {
			signIn: false,
		},
		category: 'JIGSAW',
		sliderPosition: 0,
		isDragging: false,
		startX: 0,
		startSliderPosition: 0,
		isShowPassword: false,
		loginType:'MOBILESMS',
	});
	// 时间获取
	const currentTime = computed(() => {
		return formatAxis(new Date());
	});

	let loginKey = ref('');
	let browser = getBrowerInfo();
	let interval: any = null;
	const getCode = () => {
		let params = { category: state.category };
		$api.common.send
			.postCrypto('login0004', params)
			.then((res) => {
				let result = res.result;
				loginKey.value = result.loginKey;
				state.originalImgSrc = result.originalImageBase64;
				state.sliderImgSrc = result.sliderImageBase64;
			})
			.catch(() => {});
	};

	// 开始拖拽
	const startDrag = (event) => {
		state.isDragging = true;
		state.startX = event.type === 'touchstart' ? event.touches[0].clientX : event.clientX;
		state.startSliderPosition = state.sliderPosition;
		document.addEventListener(event.type === 'touchstart' ? 'touchmove' : 'mousemove', doDrag);
		document.addEventListener(event.type === 'touchstart' ? 'touchend' : 'mouseup', stopDrag);
	};

	// 拖拽中
	const doDrag = (event) => {
		if (!state.isDragging) return;

		const currentX = event.type === 'touchmove' ? event.touches[0].clientX : event.clientX;
		const diffX = currentX - state.startX;
		const maxPosition = document.querySelector('.captcha-bg').width - 50; // 滑块宽度假设为50px

		state.sliderPosition = Math.min(maxPosition, Math.max(0, state.startSliderPosition + diffX));
	};

	// 停止拖拽
	const stopDrag = (event) => {
		if (!state.isDragging) return;
		state.isDragging = false;
		document.removeEventListener(event.type === 'touchend' ? 'touchmove' : 'mousemove', doDrag);
		document.removeEventListener(event.type === 'touchend' ? 'touchend' : 'mouseup', stopDrag);
	};

	onMounted(() => {
		getCode();		
		//获取路由配置中param参数
		const route = useRoute()
		let query = route.query
		if (query.loginType === 'SMS') {
			state.loginType = query.loginType;
		} 
	});
	const sendMessage = (formEl: FormInstance | undefined) => {
		if (!formEl) return;
		if (state.disableCodeBtn) {
			return;
		}
		let fieldsToValidate = ['cellphone'];
		Promise.all(
			fieldsToValidate.map((item: string) => {
				return new Promise((resolve) => {
					formEl.validateField(item, (valid) => {
						resolve(valid);
					});
				});
			})
		).then((valids) => {
			let m = valids.filter((valid) => !valid).length > 0;
			if (!m) {
				state.disableCodeBtn = true;

				interval = window.setInterval(() => {
					if (state.msgForm.time-- <= 0) {
						state.msgForm.time = 60;
						state.disableCodeBtn = false;
						state.msgForm.smsSendBtn = false;
						state.msgForm.smsText = '重新发送';
						window.clearInterval(interval);
						getCode();
					}
				}, 1000);
				let params = {
					loginKey: loginKey.value,
					category: state.category,
					loginType: state.loginType,
					equipmentType: 'pc',
					smsSendType:'login'
				};
				params = Object.assign(params, state.ruleForm);
				$api.common.send
					.postCrypto('login0005', params,null,true)
					.then(() => {
						ElMessage.success('短信发送成功');
						state.disableCodeBtn = true;
						state.msgForm.smsSendBtn = true;
					})
					.catch(() => {
						window.clearInterval(interval);
						state.msgForm.time = 60;
						state.disableCodeBtn = false;
						state.msgForm.smsSendBtn = false;
						state.msgForm.smsText = '获取验证码';
					});
			}
		});
	};
	const imgChange = (value: any) => {
		if (state.msgForm.smsSendBtn) {
			state.disableCodeBtn = true;
			return;
		}
		if (value && value.length < 4) {
			state.disableCodeBtn = true;
		} else {
			state.disableCodeBtn = false;
		}
	};
	const imgClear = () => {
		state.disableCodeBtn = true;
	};
	const HOME_PATH = import.meta.env.VITE_HOME_PATH as string;
	const VUE_APP_NAME = import.meta.env.VITE_APP_NAME as string;
	const VUE_APP_CODE = import.meta.env.VITE_APP_CODE as string;
	const VUE_APP_VERSION = import.meta.env.VITE_APP_VERSION as string;
	const themeConfig = store.theme;
	// 登录
	const onSignIn = (formEl: FormInstance | undefined) => {
		if (!formEl) return;
		formEl.validate((valid) => {
			if (valid) {
				signIn().catch(() => {
					state.loading.signIn = false;
					getCode();
				});
			} else {
				return false;
			}
		});
	};
	const signIn = async () => {
		state.loading.signIn = true;
		let loginParams = {
			loginType: state.loginType,
			equipmentType: 'pc',
			browser: browser.browserType,
			loginKey: loginKey.value,
			userPassword: '',
			systemVersion: VUE_APP_VERSION,
			systemCode: VUE_APP_CODE,
			systemName: VUE_APP_NAME,
			category: state.category,
		};
		loginParams = Object.assign(loginParams, state.ruleForm);
		if (loginParams.userPassword) {
			loginParams.userPassword = MD5(loginParams.userPassword);
		}
		let res = await $api.common.login.post(loginParams)
		
		if (res) {
			let sessionData = {};
			await $api.common.getUserInfo.post(sessionData);
			if (!themeConfig.isRequestRoutes) {
				// 前端控制路由，2、请注意执行顺序
				await initFrontEndControlRoutes();
				signInSuccess(false);
			} else {
				// 模拟后端控制路由，isRequestRoutes 为 true，则开启后端控制路由
				// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
				await initBackEndControlRoutes();
				// 执行完 initBackEndControlRoutes，再执行 signInSuccess
				signInSuccess(false);
			}
		}else {
			state.loading.signIn = false;
			getCode();
		}
	};
	// 登录成功后的跳转
  const signInSuccess = (isNoPower: boolean | undefined) => {
    if (isNoPower) {
      ElMessage.warning('抱歉，您没有登录权限');
      Session.clear();
    } else {
      // 初始化登录成功时间问候语
      let currentTimeInfo = currentTime.value;
      // 登录成功，跳到转首页
      // 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
      // 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
      if (route.query?.redirect) {
        router.push({
          path: <string>route.query?.redirect,
          query: Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
        });
      } else {
        router.push(HOME_PATH);
      }
      // 登录成功提示
      const signInText = '欢迎回来！';
      ElMessage.success(`${currentTimeInfo}，${signInText}`);
      // 添加 loading，防止第一次进入界面时出现短暂空白
      NextLoading.start();
    }
    state.loading.signIn = false;
	};
	onUnmounted(() => {
		if (interval) {
			window.clearInterval(interval);
		}
	});
	return {
		sendMessage,
		onSignIn,
		captchaImageContainer,
		startDrag,
		stopDrag,
		ruleFormRef,
		getCode,
		...toRefs(state),
	};
}
